import React from 'react'
import { Button, Form, Input, DatePicker, Row, Col, TreeSelect, Table, message, Modal, Tag } from 'antd';
import {
  SettingOutlined,
  EyeOutlined,
  UserOutlined,
  StarOutlined,
  SkinOutlined,
  PhoneOutlined,
  MailOutlined,
  HomeOutlined,
  SmileOutlined,
  ClockCircleOutlined,
  LoginOutlined,
  MessageOutlined
} from '@ant-design/icons'
import { getUserApi, delUserApi, downloadInfoApi } from '../../../apis/system';
import EditUser from './EditUser';
const { RangePicker } = DatePicker
export default function User() {

  const [data, setData] = React.useState([])
  const [total, setTotal] = React.useState(0)
  const [current, setCurrent] = React.useState(1)
  const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
  const [curUserInfo, setCurUserInfo] = React.useState(null)
  const [isShowDrawer, setIsShowDrawer] = React.useState(false)
  const [sortedInfo, setSortedInfo] = React.useState({})
  const [filteredInfo, setFilteredInfo] = React.useState({});
  const [tableParams, setTableParams] = React.useState({})
  const [searchParams, setSearchParams] = React.useState({})
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [showItem, setShowItem] = React.useState({})
  const checkedItemsRef = React.useRef([])
  const searchRef = React.useRef(null)
  React.useEffect(() => {
    getUserData()
    console.log(1);
  }, [])

  // 获取数据
  function getUserData(params) {
    getUserApi(params).then(res => {
      // console.log(res);
      setData(res.rows)
      setTotal(res.total)
    })
  }

  // 选中
  const onSelectChange = (newSelectedRowKeys, selectedRows) => {
    // console.log(selectedRows);
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    checkedItemsRef.current = selectedRows
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  // 删除
  function del() {
    // console.log(checkedItemsRef.current);
    if (!checkedItemsRef.current.length) {
      message.info('请选择要删除的用户')
    } else {
      const ids = checkedItemsRef.current.map(item => item.userId).join(',')
      const names = checkedItemsRef.current.map(item => item.username).join(',')
      Modal.confirm({
        title: '提示',
        content: <div>
          确定删除以下用户吗?<br />
          {names}
        </div>,
        onOk() {
          delUserApi(ids).then(() => {
            checkedItemsRef.current = []
            getUserData()
            message.success('删除成功')
            setCurrent(1)
          })
        }
      })
    }
  }

  function add() {
    setIsShowDrawer(true)
  }

  function editUser(item) {
    setIsShowDrawer(true)
    setCurUserInfo(item)
  }

  function closeDrawer(flag) {
    setIsShowDrawer(false)
    setCurUserInfo(null)
    if (flag == 'update') {
      getUserData()
      setCurrent(1)
    }
  }

  // 表格换页，排序，筛选
  const handleChange = (pagination, filters, sorter) => {
    // console.log('Various parameters', pagination, filters, sorter);
    console.log('filters', filters);
    console.log('sorter', sorter);
    console.log(pagination);
    setFilteredInfo(filters);
    setSortedInfo(sorter);
    setCurrent(pagination.current)
    // console.log(sortedInfo);
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    }
    if (sorter.field && sorter.order) {
      params.sortOrder = sorter.order
      params.sortField = sorter.field
    }
    if (filters.ssex) {
      params.ssex = filters.ssex[0]
    }
    if (filters.status) {
      params.status = filters.status[0]
    }
    setTableParams(params)
    getUserData({ ...searchParams, ...params })
  };

  // 重置
  function reset() {
    setFilteredInfo({})
    setSortedInfo({})
    setTableParams({})
    setSearchParams({})
    setCurrent(1)
    searchRef.current.resetFields()
    getUserData()
  }

  // 查询
  const onFinish = (values) => {
    console.log('Success:', values);
    const params = {
      username: values.username,
      deptId: values.deptId,
    }
    if (values.time) {
      params.createTimeFrom = values.time[0].format('YYYY-MM-DD')
      params.createTimeTo = values.time[1].format('YYYY-MM-DD')
    }
    setSearchParams(params)
    getUserData({ ...tableParams, ...params })
  };

  function download() {
    downloadInfoApi('user')
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


  const showModal = (item) => {
    setIsModalOpen(true);
    setShowItem(item)
    console.log(item);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      sorter: true,
      sortOrder: sortedInfo.field == 'username' ? sortedInfo.order : null,
      // key: 'username'
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      // key:'ssex',
      render: (text) => {
        return sexText(text)
      },
      filterMultiple: false,
      filteredValue: filteredInfo.ssex || null,
      filters: [
        { text: '男', value: '0' },
        { text: '女', value: '1' },
        { text: '保密', value: '2' },
      ]
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      // key:'email'
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      // key:'deptName'
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      // key:'mobile'
    },
    {
      title: '状态',
      dataIndex: 'status',
      // key:'status'
      render: (text) => {
        return statusText(text)
      },
      filterMultiple: false,
      filteredValue: filteredInfo.status || null,
      filters: [
        { text: '锁定', value: '0' },
        { text: '有效', value: '1' },
      ]
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      sortOrder: sortedInfo.field == 'createTime' ? sortedInfo.order : null,
    },
    {
      title: '操作',
      render: (item) => (
        <div>
          <SettingOutlined style={{ color: '#1890ff', marginRight: '10px' }} onClick={() => editUser(item)} />
          <EyeOutlined style={{ color: 'rgb(66, 185, 131)' }} onClick={() => showModal(item)} />
        </div>


      )
    }
  ];

  function sexText(value) {
    switch (value) {
      case '0':
        return '男'
      case '1':
        return '女'
      case '2':
        return '保密'
    }
  }
  function statusText(value) {
    switch (value) {
      case '0':
        return <Tag color='red'>锁定</Tag>
      case '1':
        return <Tag color='green'>有效</Tag>
    }
  }

  return (
    <div>
      <Form
        name="basic"
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 18,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        ref={searchRef}
      >
        <Row>
          <Col span={12}>
            <Form.Item
              label="用户名"
              name="username"
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="部门" name='deptId'>
              <TreeSelect
                treeData={[
                  {
                    title: '开发部',
                    value: 1,
                    children: [
                      {
                        title: '开发一部',
                        value: 2,
                      },
                      {
                        title: '开发二部',
                        value: 3,
                      },
                    ],
                  },
                  {
                    title: '市场部',
                    value: 4,
                  },
                  {
                    title: '人事部',
                    value: 5
                  },
                  {
                    title: '测试部',
                    value: 6
                  }
                ]}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item label="创建时间" name='time'>
              <RangePicker />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              wrapperCol={{
                offset: 16,
                // span: 16,
              }}
              labelAlign={'right'}
            >

              <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                查询
              </Button>
              <Button onClick={reset}>
                重置
              </Button>

            </Form.Item>
          </Col>
        </Row>
      </Form>
      <Button type='primary' ghost={true} style={{ marginRight: '20px', marginBottom: '20px' }} onClick={add}>新增</Button>
      <Button onClick={del} style={{ marginRight: '20px' }}>删除</Button>
      <Button onClick={download}>
        导出Excel
      </Button>
      <Table
        columns={columns}
        dataSource={data}
        rowKey='userId'
        pagination={{ total, current, pageSizeOptions: ['10', '20', '30'], showSizeChanger: true, showQuickJumper: true }}
        rowSelection={rowSelection}
        onChange={handleChange}
      />
      <EditUser curUserInfo={curUserInfo} visible={isShowDrawer} closeDrawer={closeDrawer}></EditUser>

      <Modal title="用户信息" open={isModalOpen} onCancel={handleCancel} footer={null} width={800} className='userInfoModal'>
        <Row gutter={24}>
          <Col span={5}>
            <img src={"http://xawn.f3322.net:8002/distremote/static/avatar/" + showItem.avatar} alt="" width={115} height={115} />
          </Col>
          <Col span={10}>
            <p><UserOutlined />账户：{showItem.username}</p>
            <p><StarOutlined />角色：{showItem.roleName}</p>
            <p><SkinOutlined />性别：{sexText(showItem.ssex)}</p>
            <p><PhoneOutlined />电话：{showItem.mobile}</p>
            <p><MailOutlined />邮箱：{showItem.email}</p>
          </Col>
          <Col span={9}>
            <p><HomeOutlined />部门：{showItem.deptName}</p>
            <p><SmileOutlined />状态：{statusText(showItem.status)}</p>
            <p><ClockCircleOutlined />创建时间：{showItem.createTime}</p>
            <p><LoginOutlined />最近登录：{showItem.lastLoginTime}</p>
            <p><MessageOutlined />描述：{showItem.description}</p>
          </Col>
        </Row>
      </Modal>
    </div>
  )
}
